package cn.com.qtgl.tenant.comp.service;

import cn.com.qtgl.tenant.api.TenantInitStep;
import cn.com.qtgl.tenant.model.entity.TenantInfo;
import cn.com.qtgl.tenant.model.enums.InitStatus;
import cn.melonlib.cores.commons.comp.service.impl.WorkerBasicService;
import cn.melonlib.cores.identification.model.entity.Organization;
import cn.melonlib.cores.jpa.model.bean.impl.DefaultQuery;
import cn.melonlib.cores.model.anno.*;
import cn.melonlib.record.oper.anno.OperatorRecordService;
import cn.melonlib.record.oper.enums.OperatorRecordMode;
import org.hibernate.service.spi.ServiceException;
import org.intellij.lang.annotations.Language;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.List;

@Service
@WorkerComment("租户信息")
@WorkerService(
        module = "tenant"
        ,model = @WorkerModel(
                modelType = TenantInfo.class
)
)
@OperatorRecordService(mode = OperatorRecordMode.WORKER)
public class TenantInfoService extends WorkerBasicService<TenantInfo> {

    @Resource
    private TenantInitStep tenantInitStep;

    @WorkerComment("获取租户信息")
    @WorkerQuery
    public TenantInfo getTenantInfo(@WorkerParameter(value = "tenantCode") String tenantCode){
        @Language("HQL") String query="from TenantInfo where tenantCode=?1";
        List<TenantInfo> infos=dao.<List<TenantInfo>, DefaultQuery>search(new DefaultQuery(query, List.of(tenantCode))).getResult();
        if(infos.isEmpty()){
            return null;
        }
        return infos.get(0);
    }

    @WorkerComment("是否初始化")
    @WorkerQuery
    public TenantInfo initStatus(@WorkerParameter(value = "tenantCode") String tenantCode){
        @Language("HQL") String query="from TenantInfo where tenantCode=?1";
        List<TenantInfo> infos=dao.<List<TenantInfo>,DefaultQuery>search(new DefaultQuery(query, List.of(tenantCode))).getResult();
        if(infos.isEmpty()){
            return null;
        }
        return infos.get(0);
    }

    @WorkerComment("开始初始化租户")
    @WorkerStore
    @Transactional(value = Transactional.TxType.REQUIRED,rollbackOn = Exception.class)
    public TenantInfo startInitTenant(){
        Organization organization= getIdentificationMessenger().getOrganization();
        @Language("HQL") String query="from TenantInfo where tenantCode=?1";
        List<TenantInfo> tenantInfoList=dao.<List<TenantInfo>,DefaultQuery>search(new DefaultQuery(query, List.of(organization.getCode()))).getResult();
        if(tenantInfoList.size()>0){
            TenantInfo info=tenantInfoList.get(0);
            info.setTenantConfig("{}");
            info=dao.save(info).getResult();
            String message=tenantInitStep.start(info);
            info.setInitMessages(message);
            dao.save(info);
            return info;
        }else {
            TenantInfo tenantInfo=new TenantInfo();
            tenantInfo.setTenantCode(organization.getCode());
            tenantInfo.setTenantConfig("{}");
            tenantInfo.setInitStep(0);
            tenantInfo.setStatus(InitStatus.START);
            tenantInfo.setTenantName(organization.getName());
            tenantInfo=dao.save(tenantInfo).getResult();
            String message=tenantInitStep.start(tenantInfo);
            tenantInfo.setInitMessages(message);
            dao.save(tenantInfo);
            return tenantInfo;
        }
    }
    @WorkerComment("初始化租户步骤记录")
    @WorkerStore
    @Transactional(value = Transactional.TxType.REQUIRED,rollbackOn = Exception.class)
    public TenantInfo stepInitTenant(@WorkerParameter(value = "step",comment = "步骤",required = true) Integer step){
        Organization organization= getIdentificationMessenger().getOrganization();
        @Language("HQL") String query="from TenantInfo where tenantCode=?1";
        List<TenantInfo> tenantInfoList=dao.<List<TenantInfo>,DefaultQuery>search(new DefaultQuery(query, List.of(organization.getCode()))).getResult();
        if(tenantInfoList.size()>0){
            TenantInfo info=tenantInfoList.get(0);
            info.setTenantConfig("{}");
            info.setStatus(InitStatus.DOING);
            info.setInitStep(step);
            info= dao.save(info).getResult();
            String message=tenantInitStep.step(info,step);
            info.setInitMessages(message);
            dao.save(info);
            return info;
        }else{
            throw new ServiceException("未匹配到租户信息，请重新开始");
        }
    }
    @WorkerComment("完成初始化租户")
    @WorkerStore
    @Transactional(value = Transactional.TxType.REQUIRED,rollbackOn = Exception.class)
    public TenantInfo doneInitTenant(@WorkerParameter(value = "step",comment = "步骤",required = true) Integer step){
        Organization organization= getIdentificationMessenger().getOrganization();
        @Language("HQL") String query="from TenantInfo where tenantCode=?1";
        List<TenantInfo> tenantInfoList=dao.<List<TenantInfo>,DefaultQuery>search(new DefaultQuery(query, List.of(organization.getCode()))).getResult();
        if(tenantInfoList.size()>0){
            TenantInfo info=tenantInfoList.get(0);
            info.setTenantConfig("{}");
            info.setStatus(InitStatus.DONE);
            info.setInitStep(step);
            info=dao.save(info).getResult();
            String message=tenantInitStep.done(info);
            info.setInitMessages(message);
            dao.save(info);
            return info;
        }else{
            throw new ServiceException("未匹配到租户信息，请重新开始");
        }
    }

    @WorkerComment("初始化租户出错")
    @WorkerStore
    @Transactional(value = Transactional.TxType.REQUIRED,rollbackOn = Exception.class)
    public TenantInfo errorInitTenant(@WorkerParameter(value = "step",comment = "步骤",required = true) Integer step){
        Organization organization= getIdentificationMessenger().getOrganization();
        @Language("HQL") String query="from TenantInfo where tenantCode=?1";
        List<TenantInfo> tenantInfoList=dao.<List<TenantInfo>,DefaultQuery>search(new DefaultQuery(query, List.of(organization.getCode()))).getResult();
        if(tenantInfoList.size()>0){
            TenantInfo info=tenantInfoList.get(0);
            info.setTenantConfig("{}");
            info.setStatus(InitStatus.ERROR);
            info.setInitStep(step);
            info= dao.save(info).getResult();
            String message=tenantInitStep.error(info);
            info.setInitMessages(message);
            dao.save(info);
            return info;
        }else{
            throw new ServiceException("未匹配到租户信息，请重新开始");
        }
    }
}
